import serial
import sys
import time
import db
try:
    ser = serial.Serial('/dev/ttyUSB0',9600)
except Exception as e:
    print("打开串口错误")
    print(e)
    exit(1)
while True:
    line = ser.readline()
    if line:
        # ret = chardet.detect(line)  # 查看串口返回来的数据到底是什么编码！是ASCII！！
        line.decode('ascii', 'ignore')  # 以字符串的格式接收需要重新转码
        line = str(line, 'utf-8')  # 转换成 'utf-8' 编码
        # 去除回车和换行
        line = line.replace('\n', '').replace('\r', '')  

        if line[0:4] == "+CSQ":
            temp_xh = 0
            xh1 = line[5:].split(",")
            for temp in xh1:
                temp_xh = int(temp) + temp_xh
            
            
            xh = str(temp_xh)
            now_date = time.strftime('%Y-%m-%d',time.localtime(time.time()))    #获取当前日期
            now_time = time.strftime('%H:%M:%S',time.localtime(time.time()))    #获取当前时间
            print("北斗地址:"+bh,end="  ")
            print("湿度:"+sd,end="  ")
            print("温度:"+wd,end="  ")
            print("信号:"+xh,end="  ")
            print("光敏:"+gm,end="  ")
            print("震动:1",end="  ")
            print("烟雾:"+yw,end="  ")
            print("时间:"+now_date+"  "+now_time,end="\n")
            db.insert(bh,wd,sd,xh,gm,zd,yw,now_date,now_time)
            

        if line[0:4] == "RDSS":
            line1 = line.split(',')
            bh = line1[1][1:]   #北斗地址
            if bh== "961583":
                sd = line1[2].split(':')[1] #湿度
                wd = line1[3].split(':')[1] #温度
                gm = line1[4].split(':')[1] #光敏
                zd = 1                      #震动
                yw = line1[5].split(':')[1] #烟雾
                ser.write('AT+CSQ?'.encode())
